import React from "react";
import { Form, Input, Button, message as antdMessage } from "antd";
import "./style.css";
import { LoginData } from "../../types";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import { useDispatch } from 'react-redux'
const Index: React.FC = () => {
  const navigate = useNavigate()
  const dispatch = useDispatch()

  const onFinish = async (values: LoginData) => {
    const resp = await axios.post("/api/login", values);
    const { code, message, data } = resp.data;
    
    if (code === 200) {
      antdMessage.success(message);
      dispatch({ type: 'modify_user', payload: data })
      navigate('/home')
    } else {
      antdMessage.error(message);
    }
  };
  return (
    <div>
      <div className="form">
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 18 }}
          onFinish={onFinish}
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[
              {
                required: true,
                message: "用户名不可以为空",
              },
              {
                validator(rule, value) {
                  const regTel = /^1[3-9]\d{9}$/;
                  if (regTel.test(value)) {
                    return Promise.resolve();
                  } else {
                    return Promise.reject(new Error("用户名必须是手机号"));
                  }
                },
              },
            ]}
          >
            <Input></Input>
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[
              {
                required: true,
                message: "密码不可以为空",
              },
            ]}
          >
            <Input></Input>
          </Form.Item>
          <Form.Item wrapperCol={{ span: 18, offset: 4 }}>
            <Button block type="primary" size="large" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Index;
